<template>
  <div class="dept-group-management">
    <div class="content-container">
      <!-- 部门树形选择区域 -->
      <div class="dept-selector">
        <div class="tree-header">
          <h3>部门结构</h3>
          <el-input
            v-model="deptFilterText"
            placeholder="输入部门名称搜索"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="dept-tree">
          <el-tree
            ref="deptTreeRef"
            :data="deptTree"
            :props="treeProps"
            :filter-node-method="filterNode"
            node-key="Id"
            highlight-current
            :default-expand-all="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <el-button
                  v-if="selectedDeptId === data.Id"
                  type="primary"
                  size="small"
                  @click.stop="showAddDialog"
                  class="add-btn"
                >
                  <i class="el-icon-plus"></i> 添加关联
                </el-button>
              </span>
            </template>
          </el-tree>
        </div>
        <div v-if="selectedDept" class="dept-info">
          <p><strong>部门名称：</strong>{{ selectedDept.Name }}</p>
          <p v-if="selectedDept.parent"><strong>上级部门：</strong>{{ selectedDept.parent }}</p>
        </div>
      </div>

      <!-- 关联管理区域 -->
      <div class="relation-section">
        <div class="section-header">
          <h3>{{ tableTitle }}</h3>
          <el-button 
            type="danger" 
            size="small" 
            :disabled="selectedRelations.length === 0 || !selectedDeptId"
            @click="batchRemoveGroups"
          >
            <i class="el-icon-delete"></i> 批量移除
          </el-button>
        </div>

        <el-table 
          :data="tableData" 
          border 
          v-loading="loading" 
          @selection-change="handleSelectionChange"
          class="relation-table"
        >
          <el-table-column type="selection" width="45" v-if="selectedDeptId" />
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column label="组别名称" prop="Name" align="center" />
          <el-table-column label="类别" prop="Category" align="center"></el-table-column>
          <el-table-column label="备注" prop="Remark" align="center"></el-table-column>
          <el-table-column label="状态" width="100" prop="IsActive" align="center">
            <template #default="{ row }">
              <el-tag :type="row.IsActive === 'Y' ? 'success' : 'danger'" size="small">
                {{ row.IsActive === 'Y' ? '有效' : '无效' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" v-if="selectedDeptId">
            <template #default="{ row }">
              <el-button 
                size="small" 
                @click="editRelationStatus(row)"
                :type="row.IsActive === 'Y' ? 'warning' : 'success'"
              >
                {{ row.IsActive === 'Y' ? '禁用' : '启用' }}
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="removeRelation(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加关联对话框 -->
    <el-dialog 
      v-model="addDialogVisible" 
      :title="`为 ${selectedDept?.Name || '部门'} 添加组别关联`" 
      width="600px"
    >
      <div class="dialog-content">
        <div class="available-groups">
          <h4>选择组别</h4>
          <el-table :data="availableGroups" border height="400">
            <el-table-column type="selection" width="45" />
            <el-table-column label="组别名称" prop="Name" />
            <el-table-column label="类别" prop="Category" />
            <el-table-column label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.IsActive === 'Y' ? 'success' : 'danger'" size="small">
                  {{ row.IsActive === 'Y' ? '有效' : '无效' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addSelectedGroups">保存</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import {
  getAllDepts,
  getAllGroups,
  getDeptGroups,
  getAvailableGroupsForDept,
  addGroupsToDept,
  removeGroupsFromDept,
  updateDeptGroupStatus,
  deleteDeptGroup
} from '@/api/system/deptGroup'

// 类型定义
interface Dept {
  Id: string
  Name: string
  parent?: string
  children?: Dept[]
}

interface Group {
  Id: string
  Name: string
  Category: string
  IsActive: string
  Remark?: string
}

interface DeptGroupRelation {
  id: string
  deptId: string
  groupId: string
  IsActive: string
  CreatedAt: string
  ModifiedAt: string
  Name?: string
  Category?: string
}

// 数据状态
const deptTree = ref<Dept[]>([])
const groups = ref<Group[]>([])
const relations = ref<DeptGroupRelation[]>([])
const availableGroups = ref<Group[]>([])
const selectedDeptId = ref<string>('')
const selectedDept = ref<Dept | null>(null)
const addDialogVisible = ref(false)
const loading = ref(false)
const selectedRelations = ref<DeptGroupRelation[]>([])
const deptTreeRef = ref()
const deptFilterText = ref('')
const selectedGroups = ref<Group[]>([])

// 树形结构配置
const treeProps = {
  children: 'children',
  label: 'Name'
}

// 计算属性
const tableTitle = computed(() => {
  return selectedDeptId.value 
    ? '已关联组别' 
    : '所有组别信息'
})

const tableData = computed(() => {
  if (selectedDeptId.value) {
    return relations.value.map(rel => {
      const group = groups.value.find(g => g.Id === rel.groupId)
      return {
        ...rel,
        ...group
      }
    })
  } else {
    return groups.value
  }
})

// 方法
const fetchDeptTree = async () => {
  try {
    loading.value = true
    const response = await getAllDepts()
    // 将扁平数据转换为树形结构
    const deptMap: Record<string, Dept> = {}
    const tree: Dept[] = []
    
    // 第一遍：创建映射
    response.Data.forEach((dept: any) => {
      deptMap[dept.Id] = { ...dept, children: [] }
    })
    
    // 第二遍：构建树
    response.Data.forEach((dept: any) => {
      if (dept.ParentId && deptMap[dept.ParentId]) {
        deptMap[dept.ParentId].children!.push(deptMap[dept.Id])
      } else {
        tree.push(deptMap[dept.Id])
      }
    })
    
    deptTree.value = tree
  } catch (error) {
    ElMessage.error('获取部门树失败')
  } finally {
    loading.value = false
  }
}

const fetchAllGroups = async () => {
  try {
    loading.value = true
    const res = await getAllGroups()
    if (res.Code == 200 && res.Data != null) {
      groups.value = res.Data
    }
  } catch (error) {
    ElMessage.error('获取组别列表失败')
  } finally {
    loading.value = false
  }
}

const handleNodeClick = async (data: Dept) => {
  selectedDeptId.value = data.Id
  selectedDept.value = data
  
  try {
    loading.value = true
    // 获取部门关联的组别
    const relationsResponse = await getDeptGroups(data.Id)
    relations.value = relationsResponse.Data ?? []
    
    // 获取可用组别
    const availableResponse = await getAvailableGroupsForDept(data.Id)
    availableGroups.value = availableResponse.Data ?? []
  } catch (error) {
    ElMessage.error('获取部门关联信息失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  if (!selectedDeptId.value) {
    ElMessage.warning('请先选择部门')
    return
  }
  addDialogVisible.value = true
}

const addSelectedGroups = async () => {
  if (!selectedDeptId.value || selectedGroups.value.length === 0) {
    ElMessage.warning('请选择要添加的组别')
    return
  }

  try {
    const groupIds = selectedGroups.value.map(g => g.Id)
    await addGroupsToDept(selectedDeptId.value, groupIds)
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    handleNodeClick(selectedDept.value!)
  } catch (error) {
    ElMessage.error('添加关联失败')
  }
}

const removeRelation = (relationId: string) => {
  ElMessageBox.confirm('确定要删除此关联吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDeptGroup(relationId)
      ElMessage.success('删除成功')
      handleNodeClick(selectedDept.value!)
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const batchRemoveGroups = () => {
  if (selectedRelations.value.length === 0 || !selectedDeptId.value) return

  const relationIds = selectedRelations.value.map(r => r.id)
  const groupNames = selectedRelations.value
    .map(r => r.Name || '未知组别')
    .join(', ')

  ElMessageBox.confirm(`确定要移除选中的 ${selectedRelations.value.length} 个组别关联吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await removeGroupsFromDept(selectedDeptId.value, relationIds)
      ElMessage.success(`已移除: ${groupNames}`)
      handleNodeClick(selectedDept.value!)
    } catch (error) {
      ElMessage.error('移除失败')
    }
  })
}

const editRelationStatus = (relation: DeptGroupRelation) => {
  const newStatus = relation.IsActive === 'Y' ? 'N' : 'Y'
  const action = newStatus === 'Y' ? '启用' : '禁用'

  ElMessageBox.confirm(`确定要${action}此关联吗?`, '操作确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateDeptGroupStatus(relation.id, newStatus)
      ElMessage.success(`${action}成功`)
      handleNodeClick(selectedDept.value!)
    } catch (error) {
      ElMessage.error(`${action}失败`)
    }
  })
}

const handleSelectionChange = (selection: DeptGroupRelation[]) => {
  selectedRelations.value = selection
}

// 部门树搜索过滤
const filterNode = (value: string, data: Dept, node: Node) => {
  if (!value) return true
  return data.Name.includes(value)
}

watch(deptFilterText, (val) => {
  deptTreeRef.value!.filter(val)
})

// 初始化
onMounted(() => {
  fetchDeptTree()
  fetchAllGroups()
})
</script>

<style scoped>
.dept-group-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.content-container {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 20px;
}

.dept-selector,
.relation-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.dept-selector h3,
.relation-section h3 {
  margin-top: 0;
  color: #303133;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.dept-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  font-size: 14px;
}

.dept-info p {
  margin: 8px 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.relation-table {
  width: 100%;
  margin-top: 10px;
  flex: 1;
}

.group-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 0;
}

.group-card {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  transition: transform 0.3s;
}

.group-card:hover {
  transform: translateY(-5px);
}

.group-info {
  padding: 10px 0;
}

.group-Name {
  font-weight: bold;
  margin-bottom: 5px;
}

.group-category {
  font-size: 12px;
  color: #909399;
}

.empty-tip {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.tree-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.tree-header h3 {
  margin-right: 15px;
  margin-bottom: 0;
}

.search-input {
  flex: 1;
}

.dept-tree {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.add-btn {
  padding: 5px 8px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>